package cn.edu.cuc.yjsy.admin.views;

import java.io.UnsupportedEncodingException;
import java.util.Hashtable;
import java.util.Map;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;

import cn.edu.cuc.yjsy.admin.Activator;
import cn.edu.cuc.yjsy.admin.util.ILogger;
import cn.edu.cuc.yjsy.admin.util.LoggerAdvisor;
import cn.edu.cuc.yjsy.admin.util.Op;
import cn.edu.cuc.yjsy.model.ModelPackage;

public class QueryView extends ViewPart {

	public static final String ID = "cn.edu.cuc.yjsy.admin.queryView";
	private static ILogger logger = new LoggerAdvisor(QueryView.class);
	private Activator plugin;
	private Text[] textOptions;
	private Button queryButton;
	private int[] keywords = {ModelPackage.STUDENT__NUMBER, ModelPackage.STUDENT__NAME,
			ModelPackage.STUDENT__IDNUMBER};
	
	public QueryView() {
		this.plugin = Activator.getDefault();
	}

	/**
	 * @Override
	 */
	public void createPartControl(Composite parent) {
		parent.setBackground(Display.getDefault()
								.getSystemColor(SWT.COLOR_WHITE));
		Composite panel = new Composite(parent, SWT.BORDER);
		GridLayout layout = new GridLayout();
		layout.marginHeight = 0;
		layout.marginWidth = 0;
		panel.setLayout(layout);
		// top banner
		Composite banner = new Composite(panel, SWT.NONE);
		banner.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING, GridData.VERTICAL_ALIGN_BEGINNING, true, false));
		layout = new GridLayout();
		layout.marginHeight = 5;
		layout.marginWidth = 10;
		layout.numColumns = 1;
		banner.setLayout(layout);
		
		// setup bold font
		Font boldFont = JFaceResources.getFontRegistry().getBold(JFaceResources.DEFAULT_FONT);    
			
		Label l = new Label(banner, SWT.WRAP);
		l.setText(plugin.getResourceString2("str.query.banner.label"));
		l.setFont(boldFont);

		// query options
		textOptions = new Text[3];
		Composite options = new Composite(panel, SWT.NONE);
		options.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING, GridData.VERTICAL_ALIGN_BEGINNING, true, false));
		layout = new GridLayout();
		layout.marginHeight = 5;
		layout.marginWidth = 10;
		layout.numColumns = 2;
		options.setLayout(layout);
		
		// add a verify listener
		Listener listener = new Listener() {
		      public void handleEvent(Event e) {
		        String string = e.text;
		        char[] chars = new char[string.length()];
		        string.getChars(0, chars.length, chars, 0);
		        for (int i = 0; i < chars.length; i++) {
		          if (!('0' <= chars[i] && chars[i] <= '9')) {
		            e.doit = false;
		            return;
		          }
		        }
		      }};
		
		l = new Label(options, SWT.WRAP);
		l.setText(plugin.getResourceString2("str.query.option.number.label"));
		l.setFont(boldFont);
		textOptions[0] = new Text(options, SWT.SINGLE | SWT.BORDER);
		textOptions[0].addListener(SWT.Verify, listener);
		GridData data1 = new GridData();
		data1.widthHint = 120;
		data1.heightHint = 15;
		textOptions[0].setLayoutData(data1);
		
		l = new Label(options, SWT.WRAP);
		l.setText(plugin.getResourceString2("str.query.option.name.label"));
		l.setFont(boldFont);
		textOptions[1] = new Text(options, SWT.SINGLE | SWT.BORDER);
		textOptions[1].setLayoutData(data1);
		
		l = new Label(options, SWT.WRAP);
		l.setText(plugin.getResourceString2("str.query.option.idnumber.label"));
		l.setFont(boldFont);
		textOptions[2] = new Text(options, SWT.SINGLE | SWT.BORDER);
		textOptions[2].setTextLimit(18);
		textOptions[2].setLayoutData(data1);
		textOptions[2].addListener(SWT.Verify, listener);
		
	    //focus listener
	    FocusListener focusListener = new FocusListener() {
	      public void focusGained(FocusEvent e) {
	        Text t = (Text) e.widget;
	        t.selectAll();
	      }

	      public void focusLost(FocusEvent e) {
	      }
	    };
	    //mouse listener
	    MouseListener mouseListener = new MouseAdapter() {
	        public void mouseDown(final MouseEvent e) {
	          Text t = (Text) e.widget;
	          t.selectAll();
	        }
	      };
	    //key listener, Enter
	    KeyListener keyListener = new KeyListener(){

			public void keyPressed(KeyEvent e) {
				if(e.keyCode == SWT.CR || e.keyCode == SWT.LF){
					queryButton.notifyListeners(SWT.Selection, null);
				}
			}

			public void keyReleased(KeyEvent e) {
			}
	    	
	    };
	    for(int i = 0; i < textOptions.length; i++){
	    	textOptions[i].addFocusListener(focusListener);
	    	textOptions[i].addMouseListener(mouseListener);
	    	textOptions[i].addKeyListener(keyListener);
	    }
		// query button
		Composite bottom = new Composite(panel, SWT.NONE);
		bottom.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING, GridData.VERTICAL_ALIGN_BEGINNING, true, false));
		layout = new GridLayout();
		layout.marginHeight = 5;
		layout.marginWidth = 10;
		layout.numColumns = 1;
		bottom.setLayout(layout);
		queryButton = new Button(bottom, SWT.NONE);
		queryButton.setText(plugin.getResourceString2("str.query.button"));
		queryButton.addSelectionListener(new SelectionListener(){

			public void widgetDefaultSelected(SelectionEvent e) {			
			}

			public void widgetSelected(SelectionEvent e) {
				try {
					Map inputs = new Hashtable(3);
					if(!validateInput(inputs)){
						MessageDialog.openInformation(getSite().getShell(), 
								plugin.getResourceString2("str.dialog.title.label"), 
								plugin.getResourceString2("str.dialog.content.label"));
						return;
					}
					IViewPart resultView = QueryView.this.getSite().getPage().showView(QueryResultView.ID);
					((QueryResultView)resultView).doQuery(inputs);
				} catch (PartInitException e1) {
					logger.error(e1.getMessage(), "can't open QueryResultView", null, e1);
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
			}
			
		});
		
		setPartName(plugin.getResourceString2("str.view.query.title.label"));
	}

	/**
	 * @Override
	 */
	public void setFocus() {
		textOptions[0].setFocus();
	}

	boolean validateInput(Map inputs) throws UnsupportedEncodingException{
		boolean rt = false;
		for(int i = 0; i < textOptions.length; i++)
			if(textOptions[i].getText() != null && 
					textOptions[i].getText().trim().length() > 0){
				inputs.put(new Integer(keywords[i]), Op.toLocaleString(textOptions[i].getText().trim()));
				rt = true;
			}
		return rt;
	}
}
